package encryption

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// EncryptionPage 处理加密工具页面的HTTP请求
func EncryptionPage(c *gin.Context) {
	html := `
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JSON文件加解密工具</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        .card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            padding: 24px;
            margin-bottom: 24px;
        }
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 16px;
            border-bottom: 1px solid #e8e8e8;
        }
        .card-title {
            font-size: 20px;
            font-weight: 600;
            margin: 0;
        }
        .btn {
            background: #1890ff;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .btn:hover {
            background: #40a9ff;
        }
        .btn-primary {
            background: #1890ff;
        }
        .btn-success {
            background: #52c41a;
        }
        .btn-danger {
            background: #ff4d4f;
        }
        .form-group {
            margin-bottom: 16px;
        }
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
        }
        .required::after {
            content: " *";
            color: red;
        }
        .form-input {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            font-size: 14px;
            box-sizing: border-box;
        }
        .form-input:focus {
            outline: none;
            border-color: #40a9ff;
            box-shadow: 0 0 0 2px rgba(24,144,255,0.2);
        }
        textarea.form-input {
            min-height: 150px;
            font-family: monospace;
            resize: vertical;
        }
        .form-actions {
            text-align: center;
            margin-top: 24px;
        }
        .btn-space {
            margin: 0 10px;
        }
        .verification-result {
            padding: 20px;
            text-align: center;
            border-radius: 4px;
            margin-top: 20px;
        }
        .valid {
            background-color: #f6ffed;
            border: 1px solid #b7eb8f;
            color: #52c41a;
        }
        .invalid {
            background-color: #fff2f0;
            border: 1px solid #ffccc7;
            color: #ff4d4f;
        }
        .info {
            background-color: #e6f7ff;
            border: 1px solid #91d5ff;
            color: #1890ff;
        }
        h3 {
            margin-top: 0;
            margin-bottom: 10px;
        }
        .file-upload {
            position: relative;
            display: inline-block;
            width: 100%;
        }
        .file-upload-input {
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            width: 100%;
            height: 100%;
            cursor: pointer;
        }
        .file-upload-label {
            display: block;
            padding: 8px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            background: #fff;
            text-align: center;
            cursor: pointer;
        }
        .file-upload-label:hover {
            background: #f5f5f5;
        }
        .file-name {
            margin-top: 8px;
            font-size: 14px;
            color: #666;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>JSON文件加解密工具</h1>
            <p>上传JSON文件或粘贴内容进行加密/解密操作</p>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h2 class="card-title">JSON加解密</h2>
            </div>
            <form id="encryptionForm">
                <div class="form-group">
                    <label class="form-label">选择JSON文件</label>
                    <div class="file-upload">
                        <input type="file" id="fileInput" class="file-upload-input" accept=".json">
                        <div class="file-upload-label">
                            点击选择文件或拖拽文件到此处
                        </div>
                    </div>
                    <div id="fileName" class="file-name"></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label required">JSON内容</label>
                    <textarea id="jsonContent" class="form-input" placeholder="粘贴JSON内容或从文件加载"></textarea>
                </div>
                
                <div class="form-group">
                    <label class="form-label required">密码</label>
                    <input type="password" id="password" class="form-input" placeholder="请输入密码">
                </div>
                
                <div class="form-actions">
                    <button type="button" class="btn btn-primary btn-space" onclick="encryptJSON()">
                        加密
                    </button>
                    <button type="button" class="btn btn-success btn-space" onclick="decryptJSON()">
                        解密
                    </button>
                    <button type="button" class="btn btn-space" onclick="resetForm()">
                        重置
                    </button>
                </div>
            </form>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h2 class="card-title">操作结果</h2>
            </div>
            <div id="operationResult">
                <div class="verification-result info">
                    <p>执行加密或解密操作后，结果将显示在此处</p>
                </div>
            </div>
            <div class="form-actions">
                <button id="downloadBtn" class="btn btn-primary" style="display: none;" onclick="downloadResult()">
                    下载结果
                </button>
            </div>
        </div>
    </div>

    <script>
        let fileContent = '';
        let operationResult = null;

        // 文件选择处理
        document.getElementById('fileInput').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                document.getElementById('fileName').textContent = '已选择: ' + file.name;
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    fileContent = e.target.result;
                    document.getElementById('jsonContent').value = fileContent;
                };
                reader.readAsText(file);
            } else {
                document.getElementById('fileName').textContent = '';
            }
        });

        // 加密功能
        function encryptJSON() {
            const jsonContent = document.getElementById('jsonContent').value;
            const password = document.getElementById('password').value;
            
            if (!jsonContent) {
                showResult('请输入JSON内容或选择JSON文件', 'invalid');
                return;
            }
            
            if (!password) {
                showResult('请输入密码', 'invalid');
                return;
            }
            
            try {
                // 验证JSON格式
                JSON.parse(jsonContent);
            } catch (e) {
                showResult('JSON格式无效: ' + e.message, 'invalid');
                return;
            }
            
            // 发送加密请求
            fetch('/api/encryption/encrypt', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    data: jsonContent,
                    password: password
                })
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => Promise.reject(err));
                }
                return response.text();
            })
            .then(data => {
                try {
                    // 尝试解析为JSON
                    const jsonData = JSON.parse(data);
                    operationResult = JSON.stringify(jsonData, null, 2);
                    showResult('加密成功', 'valid');
                    document.getElementById('downloadBtn').style.display = 'inline-block';
                } catch (e) {
                    // 如果不是JSON，直接使用数据
                    operationResult = data;
                    showResult('加密成功', 'valid');
                    document.getElementById('downloadBtn').style.display = 'inline-block';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                if (error.message) {
                    showResult('加密过程中发生错误: ' + error.message, 'invalid');
                } else {
                    showResult('加密过程中发生错误', 'invalid');
                }
            });
        }

        // 解密功能
        function decryptJSON() {
            const jsonContent = document.getElementById('jsonContent').value;
            const password = document.getElementById('password').value;
            
            if (!jsonContent) {
                showResult('请输入加密内容或选择加密文件', 'invalid');
                return;
            }
            
            if (!password) {
                showResult('请输入密码', 'invalid');
                return;
            }
            
            // 发送解密请求
            fetch('/api/encryption/decrypt', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    data: jsonContent,
                    password: password
                })
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => Promise.reject(err));
                }
                return response.text();
            })
            .then(data => {
                operationResult = data;
                try {
                    // 尝试解析为JSON并美化
                    const jsonData = JSON.parse(data);
                    operationResult = JSON.stringify(jsonData, null, 2);
                } catch (e) {
                    // 如果不是有效的JSON，保持原样
                }
                showResult('解密成功', 'valid');
                document.getElementById('downloadBtn').style.display = 'inline-block';
            })
            .catch(error => {
                console.error('Error:', error);
                if (error.message) {
                    showResult('解密过程中发生错误: ' + error.message, 'invalid');
                } else {
                    showResult('解密过程中发生错误', 'invalid');
                }
            });
        }

        // 显示结果
        function showResult(message, type) {
            const resultDiv = document.getElementById('operationResult');
            resultDiv.innerHTML = 
                '<div class="verification-result ' + type + '">' +
                '<h3>' + message + '</h3>' +
                (operationResult ? '<pre style="text-align: left; white-space: pre-wrap; word-break: break-all;">' + operationResult.substring(0, 500) + (operationResult.length > 500 ? '...' : '') + '</pre>' : '') +
                '</div>';
        }

        // 下载结果
        function downloadResult() {
            if (!operationResult) return;
            
            const blob = new Blob([operationResult], {type: 'application/json'});
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'result.json';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }

        // 重置表单
        function resetForm() {
            document.getElementById('encryptionForm').reset();
            document.getElementById('fileName').textContent = '';
            document.getElementById('operationResult').innerHTML = 
                '<div class="verification-result info"><p>执行加密或解密操作后，结果将显示在此处</p></div>';
            document.getElementById('downloadBtn').style.display = 'none';
            fileContent = '';
            operationResult = null;
        }

        // 拖拽上传功能
        const dropArea = document.querySelector('.file-upload');
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ['dragenter', 'dragover'].forEach(eventName => {
            dropArea.addEventListener(eventName, highlight, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, unhighlight, false);
        });

        function highlight() {
            dropArea.querySelector('.file-upload-label').style.backgroundColor = '#e6f7ff';
            dropArea.querySelector('.file-upload-label').style.borderColor = '#1890ff';
        }

        function unhighlight() {
            dropArea.querySelector('.file-upload-label').style.backgroundColor = '#fff';
            dropArea.querySelector('.file-upload-label').style.borderColor = '#d9d9d9';
        }

        dropArea.addEventListener('drop', handleDrop, false);

        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            if (files.length) {
                document.getElementById('fileInput').files = files;
                const event = new Event('change', { bubbles: true });
                document.getElementById('fileInput').dispatchEvent(event);
            }
        }
    </script>
</body>
</html>
`
	c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(html))
}